package demo.thread;

import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ProductorConsumer {
  public static void main(String[] args) {
    LinkedList linkedList = new LinkedList();
    ExecutorService service = Executors.newFixedThreadPool(15);
    for (int i = 0; i < 5; i++) {
      service.submit(new Productor(linkedList, i + 1, 8));
    }
    for (int i = 0; i < 10; i++) {
      service.submit(new Consumer(linkedList, i + 1));
    }
  }

  static class Productor implements Runnable {
    private List<Integer> list;
    private int maxLength;
    private int name;

    public Productor(List list, int name, int maxLength) {
      this.list = list;
      this.name = name;
      this.maxLength = maxLength;
    }

    @Override
    public void run() {
      while (true) {
        synchronized (list) {
          try {
            while (list.size() == maxLength) {
              System.out.println(list.size() + " ������" + Thread.currentThread().getName() + "  list�Դﵽ�������������wait");
              list.wait();
              System.out.println(list.size() + " ������" + Thread.currentThread().getName() + "  �˳�wait");
            }
            Thread.sleep(500);
            Random random = new Random();
            int i = random.nextInt();
            System.out.println(list.size() + " ������" + Thread.currentThread().getName() + " ��������" + i);
            list.add(i);
            list.notifyAll();
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
        }
      }
    }
  }

  static class Consumer implements Runnable {
    private List<Integer> list;
    private int name;

    public Consumer(List list, int name) {
      this.list = list;
      this.name = name;
    }

    @Override
    public void run() {
      while (true) {
        synchronized (list) {
          try {
            while (list.isEmpty()) {
              System.out.println(list.size() + " ������" + name + "  listΪ�գ�����wait");
              list.wait();
              System.out.println(list.size() + " ������" + name + "  �˳�wait");
            }
            Thread.sleep(500);
            Integer element = list.remove(0);
            System.out.println(list.size() + " ������" + name + "  �������ݣ�" + element);
            list.notifyAll();
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
        }
      }
    }
  }
}
